<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Admin\Question;
use Excel;
use Input;
class QuestionController extends Controller
{
    //列表操作
    public function index(){
    	//获取数据
    	$data = Question::with('rel_paper') -> get();
    	//显示视图
    	return view('admin.question.index',['data' => $data]);
    }

    //导出数据
    public function export(){
    	//提供的demo
    	// $cellData = [
     //        ['学号','姓名','成绩'],	//表头
     //        ['10001','AAAAA','99'],
     //        ['10002','BBBBB','92'],
     //        ['10003','CCCCC','95'],
     //        ['10004','DDDDD','89'],
     //        ['10005','EEEEE','96'],
     //    ];
     	$question = Question::get() -> toArray();
     	$cellData = array();
     	//表头
     	$cellData[] = ['序号','题干','分值','选项','答案','创建时间'];
     	//循环出数据体
     	foreach ($question as $key => $value) {
     		$cellData[] = [$value['id'],$value['question'],$value['score'],$value['options'],$value['answer'],$value['created_at']];
     	}
     	//dd($cellData);
        Excel::create(date('YmdHis') . rand(100000,999999),function($excel) use ($cellData){
            $excel->sheet('试题', function($sheet) use ($cellData){
                $sheet->rows($cellData);
            });
        })->export('xls');
    }

    //试题的导入
    public function import(){
    	if(Input::method() == 'POST'){
    		//定义文件的路径
    		$filePath = 'public' . Input::get('excel');
    		$count = 0;//计数器
		    Excel::load($filePath, function($reader) use ($count) {
		        $data = $reader->getSheet(0)->toArray();
		        //dd($data);
		        foreach ($data as $key => $value) {
		        	//第一条记录没有用，需要跳过
		        	if($key == '0'){
		        		continue;
		        	}
		        	//数据入库
		        	$result = Question::insert([
		        			'question'	=>	$value[0],
		        			'options'	=>	$value[1],
		        			'answer'	=>	$value[2],
		        			'score'		=>	$value[3],
		        			'paper_id'	=>	Input::get('paper_id'),
		        			'created_at'=>	date('Y-m-d H:i:s')
		        		]);
		        	//判断结果
		        	// if($result){
		        	// 	$count = $count + 1;
		        	// }
		        }
		        // return response() -> json([
		        // 			'total'		=>	count($data) - 1,
		        // 			'success'	=>	$count
		        // 	]);
		    });
    	}else{
    		//获取试卷列表
	    	$paperList = \App\Admin\Paper::get();
	    	//展示视图
	    	return view('admin.question.import',['paperList' => $paperList]);
    	}
    }
}
